<template>
    <nav-bar title="添加岗位" @back="handleNavBack" :useCustomBack="true" />
    <div class="job-create">
        <!-- 岗位名称输入 -->
        <div class="form-item border">
            <div class="input">
                <van-field v-model="jobInfo.name" placeholder="请输入岗位名称" @input="handleInputChange">
                    <template #right-icon>
                        <van-icon name="arrow" @click="showJobSelector = true" />
                    </template>
                </van-field>
            </div>
        </div>

        <!-- 岗位信息输入 -->
        <div class="form-item">
            <div class="input-area">
                <van-field v-model="jobInfo.description" type="textarea" placeholder="请输入岗位信息" :autosize="true"
                    @input="handleInputChange" />
            </div>
        </div>

        <!-- 底部按钮区域 -->
        <div class="bottom-button">
            <!-- 快捷岗位选择 -->
            <div class="jobs">
                <div v-for="job in quickJobs" :key="job.id" class="job" @click="handleQuickSelect(job)">
                    {{ job.name }}
                </div>
                <div class="job more" @click="showJobSelector = true">更多岗位</div>
            </div>

            <!-- 分割线 -->
            <div class="divider">
                <span class="divider-text">或者</span>
            </div>

            <!-- 上传区域 -->
            <div class="upload-area">
                <div class="upload-btn" @click="handleUpload">
                    <van-icon name="photograph" />
                    <span>上传截图</span>
                </div>
                <div class="upload-tip">上传后自动解析并回显图片中的岗位信息</div>
            </div>

            <!-- 图片预览 -->
            <div class="preview-image" v-if="uploadedImage">
                <img :src="uploadedImage" alt="岗位截图">
                <van-icon name="close" class="close-icon" @click="removeImage" />
            </div>

            <!-- 保存按钮 -->
            <van-button block type="primary" :disabled="!canSave" v-loading="handleSave">
                保存岗位
            </van-button>
        </div>

        <!-- 岗位选择器 -->
        <job-selector :show="showJobSelector" v-model="selectedJob" @select="handleSelectJob"
            @update:show="showJobSelector = $event" />

        <!-- 未保存确认弹窗 -->
        <van-dialog v-model:show="showConfirmDialog" title="是否确定返回?" :show-cancel-button="false">
            <div class="confirm-content">
                你填写的面试岗位信息暂未保存，直接返回后将清空岗位信息
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <van-button block plain @click="handleCancel">取消</van-button>
                    <van-button block @click="handleSaveAndBack">保存并返回</van-button>
                    <van-button block plain type="danger" @click="handleDirectBack">直接返回</van-button>

                </div>
            </template>
        </van-dialog>
    </div>
</template>

<script setup>
    import { ref, onMounted, onBeforeUnmount, computed, watch } from 'vue'
    import { useRouter } from 'vue-router'
    import { showToast } from 'vant'
    import { jsonArray } from '@/utils/jsonArray'
    import { uploadFiles, ocrIdentify } from '@/api/comm'
    import JobSelector from '@/components/JobSelector/index.vue'
    import NavBar from '@/components/NavBar/index.vue'
    import { jobApi } from '@/api/job'
    const router = useRouter()

    // 状态管理
    const jobInfo = ref({
        name: '',
        description: ''
    })
    const showJobSelector = ref(false)
    const showConfirmDialog = ref(false)
    const selectedJob = ref(null)
    const uploadedImage = ref(null)
    const uploadRes = ref(null)
    // 是否已保存，初始为false，成功保存后设为true
    const isSaved = ref(false)

    // 快捷选择的岗位列表
    const quickJobs = jsonArray.quickJobs

    // 是否可以保存
    const canSave = computed(() => {
        return jobInfo.value.name && (jobInfo.value.description || uploadedImage.value)
    })

    // 判断是否有填写内容
    const hasContent = computed(() => {
        return jobInfo.value.name || jobInfo.value.description
    })

    // 选择岗位
    const handleSelectJob = (job) => {
        jobInfo.value.name = job.name
        jobInfo.value.description = job.description
        showJobSelector.value = false
        // 修改了内容，重置保存状态
        isSaved.value = false
    }

    // 快捷选择岗位
    const handleQuickSelect = (job) => {
        jobInfo.value.name = job.name
        jobInfo.value.description = job.description
        // 修改了内容，重置保存状态
        isSaved.value = false
    }

    // 处理文件上传
    const handleUpload = async () => {
        try {
            // H5环境使用input file上传
            const input = document.createElement('input')
            input.type = 'file'
            input.accept = 'image/*'
            input.onchange = async (e) => {
                const file = e.target.files[0]
                if (file) {
                    // 检查文件大小（5MB）
                    if (file.size > 5 * 1024 * 1024) {
                        showToast('图片大小不能超过5MB')
                        return
                    }

                    // 检查图片尺寸
                    const img = new Image()
                    img.src = URL.createObjectURL(file)
                    await new Promise((resolve, reject) => {
                        img.onload = () => {
                            URL.revokeObjectURL(img.src)
                            if (img.width > 8192 || img.height > 8192) {
                                showToast('图片尺寸不能超过8192x8192')
                                reject(new Error('图片尺寸过大'))
                            } else {
                                resolve()
                            }
                        }
                        img.onerror = () => {
                            URL.revokeObjectURL(img.src)
                            reject(new Error('图片加载失败'))
                        }
                    })

                    // 先上传文件
                    const formData = new FormData()
                    formData.append('file', file)
                    uploadRes.value = await uploadFiles(formData)
                    console.log(uploadRes.value)
                    // 调用OCR识别接口，传入图片的URL
                    if (uploadRes.value.code === 0) {
                        // 上传成功后调用OCR识别
                        const ocrRes = await ocrIdentify({ jd_url: uploadRes.value.data.url })
                        if (ocrRes.code === 0) {
                            jobInfo.value.description = ocrRes.data.jd_content
                            jobInfo.value.name = ocrRes.data.jd_title
                            console.log(jobInfo.value)
                            // 修改了内容，重置保存状态
                            isSaved.value = false
                        }
                    }

                    const reader = new FileReader()
                    reader.onload = (e) => {
                        uploadedImage.value = e.target.result
                        // 修改了内容，重置保存状态
                        isSaved.value = false
                    }
                    reader.readAsDataURL(file)
                }
            }
            input.click()
        } catch (error) {
            console.error('上传失败:', error)
            showToast('上传失败')
        }
    }

    // 移除上传的图片
    const removeImage = () => {
        uploadedImage.value = null
        // 修改了内容，重置保存状态
        isSaved.value = false
    }

    // 保存岗位
    const handleSave = async () => {
        if (!canSave.value) return
        try {
            // 调用保存接口
            await jobApi.createJob({
                jd_title: jobInfo.value.name,
                jd_content: jobInfo.value.description,
                jd_url: uploadRes.value ? uploadRes.value.data.url : '',
                default_status: 1
            })

            // 保存成功后设置 isSaved 为 true
            isSaved.value = true
            showToast('保存成功')
            router.back()
        } catch (error) {
            showToast('保存失败')
        }
    }

    // 检查未保存内容
    const checkUnsavedContent = () => {
        // 只有当表单有内容且未保存时，才显示确认弹窗
        if (hasContent.value && !isSaved.value) {
            showConfirmDialog.value = true
            return true
        }
        return false
    }

    // 处理导航栏的返回按钮
    const handleNavBack = () => {
        // 先检查是否有未保存的内容
        if (hasContent.value && !isSaved.value) {
            // 如果有未保存的内容，显示确认弹窗
            showConfirmDialog.value = true
        } else {
            // 如果没有未保存的内容，直接返回
            router.back()
        }
    }

    // 取消返回
    const handleCancel = () => {
        showConfirmDialog.value = false
    }

    // 保存并返回
    const handleSaveAndBack = async () => {
        await handleSave()
        router.back()
    }

    // 直接返回
    const handleDirectBack = () => {
        router.back()
    }

    // 输入变化处理
    const handleInputChange = () => {
        // 文本输入变化，重置保存状态
        isSaved.value = false
    }

    // 监听返回按钮
    onBeforeUnmount(() => {
        console.log('组件卸载')
    })
</script>

<style lang="scss" scoped>
    .job-create {
        min-height: 100vh;
        background: rgb(255, 255, 255);
        padding: 16px;
        padding-bottom: 76px;

        .border {
            border-bottom: 1px solid rgba(229, 230, 235, 1);
        }

        .input-area {
            height: 500px;
            overflow: auto;
        }

        .bottom-button {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 16px;
            background: #fff;
            box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);

            .jobs {
                display: flex;
                align-items: center;
                margin-bottom: 16px;
                overflow-x: auto;
                padding-bottom: 4px;

                &::-webkit-scrollbar {
                    display: none;
                }

                .job {
                    flex-shrink: 0;
                    padding: 8px 16px;
                    border-radius: 8px;
                    background: rgb(242, 243, 245);
                    font-size: 14px;
                    color: rgba(29, 33, 41, 1);
                    margin-right: 8px;
                    cursor: pointer;

                    &.more {
                        color: rgb(22, 93, 255);
                    }
                }
            }

            .divider {
                position: relative;
                text-align: center;
                margin: 16px 0;

                &::before {
                    content: '';
                    position: absolute;
                    left: 0;
                    top: 50%;
                    width: 100%;
                    height: 1px;
                    background: #eee;
                }

                .divider-text {
                    position: relative;
                    background: #fff;
                    padding: 0 12px;
                    color: #999;
                    font-size: 14px;
                }
            }

            .upload-area {
                text-align: center;
                padding: 32px 16px;
                background: #f5f6f7;
                border-radius: 8px;
                margin-bottom: 16px;

                .upload-btn {
                    display: inline-flex;
                    align-items: center;
                    color: rgba(29, 33, 41, 1);
                    font-size: 16px;
                    cursor: pointer;

                    .van-icon {
                        margin-right: 4px;
                        font-size: 17px;
                        font-weight: 500;
                    }
                }

                .upload-tip {
                    margin-top: 8px;
                    font-size: 12px;
                    color: #999;
                }
            }

            .van-button {
                border-radius: 8px;
                background: rgb(22, 93, 255);
                border: none;
                height: 44px;

                &--disabled {
                    background: #eee;
                    color: #999;
                }
            }
        }
    }

    .dialog-footer {
        display: flex;
        flex-direction: column;
        gap: 12px;
        padding: 16px;

        .van-button {
            height: 44px;
            border-radius: 8px;
            font-size: 16px;
        }
    }

    .confirm-content {
        padding: 20px;
        text-align: center;
        color: #666;
        font-size: 14px;
    }

    .preview-image {
        position: relative;
        margin-top: 16px;
        background: #f5f6f7;
        border-radius: 8px;
        padding: 12px;
        margin-bottom: 10px;

        img {
            width: 100%;
            max-height: 200px;
            object-fit: contain;
        }

        .close-icon {
            position: absolute;
            top: 8px;
            right: 8px;
            padding: 4px;
            background: rgba(0, 0, 0, 0.5);
            border-radius: 50%;
            color: #fff;
            cursor: pointer;
            z-index: 1;
        }
    }
</style>